#coding: utf-8

import time
import nonebot as nb
import aiocqhttp
import random
import os
import pickle
from .tools import *
from .config import *
from .command import *
    
@nb.on_websocket_connect
async def init(event: aiocqhttp.Event):
    global bot, KeywordsRepeatProb, SUPERUSERS, GroupRepeatProb
    while True:
        try:
            info = await bot.get_status()
            # print(info)
            if info['good']:
                break
            time.sleep(1)
        except:
            pass
    if not theData('load'):
        groupList = await bot.get_group_list()
        for item in groupList: # initialize
            KeywordsRepeatProb[item['group_id']] = {'abs': {}, 'inc': {}}
            SUPERUSERS[item['group_id']] = set()
            GroupRepeatProb[item['group_id']] = DEFAULT_GROUP_PROB
        nb.logger.info(__plugin_name__ + '-loadData: 初始化数据成功!')
        info = '文件写入成功!' if theData('save') else '文件写入失败!'
    else:
        nb.logger.info(__plugin_name__ + '-loadData: 读取数据文件成功!')
    await bot.send_msg(user_id=GODUSER, message="Bot Start!")

@bot.on_message('group')
async def waitCommand(event: aiocqhttp.Event) -> None:
    global SUPERUSERS, GODUSER
    if isCommand(event.raw_message):
        superUserLists = [GODUSER, *list(SUPERUSERS['all']), *list(SUPERUSERS[event.group_id])] # 生成当前管理者的列表
        if event.user_id in superUserLists:
            theResult = splitString(analysisCommand(event.raw_message, group_id=event.group_id, user_id=event.user_id))
            for message in theResult:
                await bot.send_msg(group_id=event.group_id, message=message)
            return None
        else:
            await bot.send_msg(group_id=event.group_id, 
                message="[CQ:at,qq={}] 对不起, 您还不是本屑bot的管理员喔~".format(event.user_id))

@bot.on_message('group')
async def repeater(event: aiocqhttp.Event) -> None:
    global GODUSER, SUPERUSERS, SPECIAL_GROUP
    superUserList = [GODUSER, *list(SUPERUSERS['all']), *list(SUPERUSERS[event.group_id])]
    if event.raw_message in ['帮助', 'help'] and event.user_id in superUserList:
        await bot.send_msg(group_id=event.group_id, message=HelpMsg)
        return None
    if not isCommand(event.raw_message) and event.group_id not in SPECIAL_GROUP:
        await repeatJudge(event)

@nb.scheduler.scheduled_job('interval', minutes=1)
async def _():
    info = '保存成功!' if theData('save') else "保存失败!"
    nb.logger.info(__plugin_name__ + '-autoSave: ' + info)
